package com.boang.controller.login;
import com.boang.resp.Result;

import com.google.code.kaptcha.Producer;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.Base64;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Tag(name = "验证码接口kaptcha")
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private Producer producer;

    @GetMapping("/code")
    public Result<String> getCode(HttpSession session, HttpServletResponse response) throws IOException {
        //MINE类型
        response.setContentType("image/jpeg");
        //生产验证码字符
        String code = producer.createText();
        //存储Redis
        stringRedisTemplate.opsForValue().set("kaptcha", code);
        //生产验证码图片
        BufferedImage image = producer.createImage(code);
        //流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        String base64Img = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(outputStream.toByteArray());

        return Result.ok(base64Img);
    }
}
